package com.ffapp.demo.home;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisApp;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BannerListBean;
import com.ffapp.demo.bean.BannerListData;
import com.ffapp.demo.bean.BaseListBeanXF;
import com.ffapp.demo.bean.BaseListDataListBean;
import com.ffapp.demo.bean.BasicBeanStr;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.ContactListBean;
import com.ffapp.demo.bean.HomeGrideListBean;
import com.ffapp.demo.bean.HomeGrideListData;
import com.ffapp.demo.bean.HomeOndutyPersonListBean;
import com.ffapp.demo.bean.HomeOndutyPersonListData;
import com.ffapp.demo.bean.HomeTodayAlarmInfoBean;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.bean.NewsListBean;
import com.ffapp.demo.bean.NewsListData;
import com.ffapp.demo.bean.UpdateBean;
import com.ffapp.demo.bean.UserBaseInfoUpdateCache;
import com.ffapp.demo.bean.UserDictBean;
import com.ffapp.demo.bean.UserInfoBean;
import com.ffapp.demo.bean.UserSensitiveWordsBean;
import com.ffapp.demo.bean.WeatherInfoBean2;
import com.ffapp.demo.map.AMapLocUtil;
import com.ffapp.demo.map.GPSUtil;
import com.ffapp.demo.notice.NoticeDetailActivity;
import com.ffapp.demo.other.MySmsFilter;
import com.ffapp.demo.util.Lunar;
import com.ffapp.demo.util.MyUtils;
import com.ffapp.demo.view.GlideImageLoader;
import com.ffapp.demo.view.HomeNumView;
import com.gongwen.marqueen.SimpleMF;
import com.gongwen.marqueen.SimpleMarqueeView;
import com.gongwen.marqueen.util.OnItemClickListener;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.robin.lazy.sms.SmsInfoBean;
import com.robin.lazy.sms.SmsObserver;
import com.robin.lazy.sms.SmsResponseCallback;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.ActivityTool;
import my.FileUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.StringUtil;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 资讯首页
 */
public class HomeIndexActivity extends HomeBaseActivity implements SmsResponseCallback {



    @BindView(R.id.recyclerView_grid)
    RecyclerView recyclerView_grid;


    @BindView(R.id.banner_ad)
    Banner banner_ad;
    BannerListBean mBannerList;

    @BindView(R.id.text_today_warnning_num)
    HomeNumView text_today_warnning_num;

    @BindView(R.id.text_marqueeview)
    SimpleMarqueeView text_marqueeview;
    NewsListBean mListBeanNews;


    HomeGrideListBean mListBeanEnter;
    HomeGrideListBean mListBeanEnterAll;//用户所有的权限入口
    AMapLocUtil mapLocUtil;

    long lastLocation = 0;
    public static final long TIME_LOCATION_BETWEEN = 60 * 1000;

    @BindView(R.id.text_time)
    TextView text_time;
    @BindView(R.id.text_weather_des)
    TextView text_weather_des;
    @BindView(R.id.text_weather_tempture)
    TextView text_weather_tempture;
    @BindView(R.id.img_weahter_img)
    ImageView img_weahter_img;


    @BindView(R.id.view_today_num_zone)
    View view_today_num_zone;
    @BindView(R.id.view_news)
    View view_news;

    private SmsObserver smsObserver;


    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.home_index_activity);


        recyclerView_grid.setLayoutManager(new GridLayoutManager(mContext, 4));


        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 12);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                //define span size for this position
                //some example for your first three items
                if (position < 3) {
                    return 4; //item will take 1/3 space of row
                } else {
                    return 3;
                }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        super.initData(savedInstanceState);
        BaseListDataListBean listEnter = new BaseListDataListBean();
        refreshData();
        FileUtils.deleteFile(Constants.DIR_TEMP);
        getMapCenter();
        checkCacheAndDownload();
        EventBus.getDefault().register(this);

        UpdateBean.check(mContext, false);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (smsObserver != null) {
            smsObserver.unregisterSMSObserver();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (lastLocation == 0) {
            requestLocationAndPost();
        } else {
            long timeBetween = new Date().getTime() - lastLocation;
            if (timeBetween > TIME_LOCATION_BETWEEN) {
                requestLocationAndPost();
            }
        }
        QMUIStatusBarHelper.setStatusBarDarkMode(mContext);

//        checkSmsObserver();
    }

    private final static int MESSAGE_NEWS_REFRESH = 21;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_NEWS_REFRESH:
                    getNews();
                    break;
            }
        }
    };

    @Override
    public void onDoubleClick() {
        super.onDoubleClick();
        refreshData();
    }

    void refreshData() {
        getAppEnterGrid();
        getTodayAlarm();
        getNews();
        getWeather();
        getListEnterAll();
        getWarnUnReadCount();
        refreshLoginInfo();
    }

    void getAppEnterGrid() {
        MyParams params = new MyParams();
        showProgress();
        params.put("projectNo", Constants.PROJECT_NO);

        MyHttpUtils.post(Constants.URL_HOME_APP_MODULE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mListBeanEnter = (HomeGrideListBean) result;
                        setGridEnterView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
//            mListBean = new ServiceNewListBean();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, HomeGrideListBean.class);
    }

    void setGridEnterView() {
        setWarnUnRead();
        recyclerView_grid.setAdapter(new AdapterEnter());
    }

    void getNews() {
        MyParams params = new MyParams();
        showProgress();
        params.put(BaseListBeanXF.PAGE_NAME, "1");
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, "3");

        MyHttpUtils.post(Constants.URL_NOTICE_LIST, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mListBeanNews = (NewsListBean) result;
                        setNewsView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, NewsListBean.class);
    }

    void setNewsView() {
        if (mListBeanEnterAll != null && mListBeanEnterAll.searchDataByName("通知公告") != null) {
            view_news.setVisibility(View.VISIBLE);
        } else {
            view_news.setVisibility(View.GONE);
        }

        if (mListBeanNews == null || mListBeanNews.getList().size() == 0) {
            view_news.setVisibility(View.GONE);
        } else {
//            view_news.setVisibility(View.VISIBLE);
            if (text_marqueeview.isFlipping()) {
                text_marqueeview.stopFlipping();
            }
            SimpleMF<String> marqueeFactory = new SimpleMF(this);
            marqueeFactory.setData(mListBeanNews.getListStr());
            text_marqueeview.setMarqueeFactory(marqueeFactory);
            text_marqueeview.startFlipping();
            text_marqueeview.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClickListener(View mView, Object mData, int mPosition) {
                    NewsListData newsListData = mListBeanNews.getList().get(mPosition);

                    if (newsListData.getIsSync_BOOLEAN()) {
                        showToast("请前往内网查看详情");
                    } else {
                        if (mListBeanEnterAll != null) {
                            HomeGrideListData data = mListBeanEnterAll.searchDataByName("通知公告");
                            if (data != null && !TextUtils.isEmpty(newsListData.getId())) {
//                                String urlDetal = data.getUrl().replace("/notice", "/noticeDetail?id=" + newsListData.getId());
//                                WebViewX5Activity.toWebView(mContext, urlDetal, data.getName());
                                NoticeDetailActivity.toDetail(mContext, newsListData.getId());
                            }
                        }
                    }
                }
            });
//            text_marqueeview.startFlipping();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        text_marqueeview.startFlipping();
    }

    @Override
    protected void onStop() {
        super.onStop();
        text_marqueeview.stopFlipping();
    }

    void getWeather() {
        MyParams params = new MyParams();
        showProgress();
//        params.put(BaseListBeanXF.PAGE_NAME, "1");
//        params.put(BaseListBeanXF.PAGE_SIZE_NAME, "3");

        Request.Builder buildRquest = new Request.Builder()
//                .url("https://apip.weatherdt.com/plugin/data?key=GdyuUL2tQT&location=101230201")
                .url("https://api.seniverse.com/v3/weather/now.json?key=tpybtyhiwonrppvl&location=xiamen&language=zh-Hans&unit=c")
                .get();
        Request request = buildRquest.build();
        MyHttpUtils.getAsyncHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                LogUtil.i("getWeather  onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String responseBody = response.body().string();
//                LogUtil.i("getWeather  onResponse:" + responseBody);
                weatherInfoBean = (WeatherInfoBean2) JSON.parseObject(responseBody, WeatherInfoBean2.class);
                JSONObject jsonObject = JSON.parseObject(responseBody);
//                LogUtil.i("weatherInfoBean == null ?---->" + (weatherInfoBean == null));
//                LogUtil.i("jsonObject == null ?---->" + (jsonObject == null));
                if (isFinishing()) return;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setWeatherView();
                    }
                });
            }
        });
    }

    WeatherInfoBean2 weatherInfoBean;

    void setWeatherView() {
        if (weatherInfoBean == null) return;
        if(weatherInfoBean.getResults() == null || weatherInfoBean.getResults().size() == 0)return;
        text_weather_des.setText(weatherInfoBean.getResults().get(0).getNow().getText());
        text_weather_tempture.setText(weatherInfoBean.getResults().get(0).getNow().getTemperature());

        Calendar today = Calendar.getInstance();
        today.setTime(new Date());
        Lunar lunar = new Lunar(today);

        text_time.setText(TimeUtils.getCurrentTimeByFormat("yyyy年MM月dd日") + "  农历 " + lunar.toString() + "  " + TimeUtils.getWeek());

//        String code = weatherInfoBean.getIMG_CODE();
        String code = weatherInfoBean.getResults().get(0).getNow().getCode();
//        String url_img = "https://apip.weatherdt.com/h5/static/images/cond-" + code + "d.png";
        String url_img = "https://s1.sencdn.com/web/icons/white/" + code + "@2x.png";
        BasisApp.loadImg(mContext, url_img, img_weahter_img);
    }

    void getTodayAlarm() {
        if (mListBeanEnterAll != null && mListBeanEnterAll.searchDataByName("警情管理") == null) {
            return;
        }
        MyParams params = new MyParams();
        showProgress();
//        params.put("projectNo", Constants.PROJECT_NO);
        if(LoginBean.getInstance().getUserInfo().isUserCompany() && LoginBean.getInstance().getUserInfo().getLatitude() != 0){
            UserInfoBean bean = LoginBean.getInstance().getUserInfo();
            params.put("longitude",bean.getLongitude());
            params.put("latitude",bean.getLatitude());
            params.put("userGroup",bean.getUserGroup());
        }
        MyHttpUtils.post(Constants.URL_HOME_TODAY_ALARM_COUNT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        HomeTodayAlarmInfoBean infoBean = (HomeTodayAlarmInfoBean) result;
//                        text_today_warnning_num.setString(infoBean.getAlarmCount() + "");
                        text_today_warnning_num.setString(infoBean.getAlarmCount_STR());
                        if (mListBeanEnterAll != null && mListBeanEnterAll.searchDataByName("警情管理") != null) {
                            view_today_num_zone.setVisibility(View.VISIBLE);
                        } else {
                            view_today_num_zone.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
//            mListBean = new ServiceNewListBean();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, HomeTodayAlarmInfoBean.class);
    }


    void requestLocationAndPost() {
        if (mapLocUtil == null) {
            mapLocUtil = new AMapLocUtil(mContext);
        }
        LogUtil.i("首页--》请求定位");
        mapLocUtil.starLocation(aMapLocationListener);

        getSensitiveWords();
        uploadPhoneInfo();
    }

    AMapLocationListener aMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (isFinishing()) return;
            LogUtil.i("首页--》onLocationChanged--\n-getLatitude-" + aMapLocation.getLatitude() + "---getLongitude-" + aMapLocation.getLongitude()+"---address---"+aMapLocation.getAddress());
//            aMapLocation.setAddress("");
            AMapLocUtil.mLocation = aMapLocation;
            mapLocUtil.reverseLocation(aMapLocation);
            postLocation(aMapLocation);
        }
    };

    void postLocation(AMapLocation aMapLocation) {
        if (isFinishing()) return;
        if (aMapLocation == null) return;
        if (aMapLocation.getLatitude() == 0) return;
        if (aMapLocation.getLongitude() == 0) return;
        MyParams params = new MyParams();
        double[] location = GPSUtil.gcj02_To_Gps84(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        params.put("longitude", location[1]);
        params.put("latitude", location[0]);
        params.put("speed", aMapLocation.getSpeed());
        params.put("angle", "");
        params.put(MyParams.PARAMS_LOG, false+"");
        MyHttpUtils.post(Constants.URL_HOME_LOCATION_UPLOAD, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        BasisBean basisBean = (BasisBean) result;
                        lastLocation = new Date().getTime();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, BasisBean.class);
    }

    private void getBannerAd() {
        mBannerList = new BannerListBean();
        for (int i = 0; i < 1; i++) {
            BannerListData banner_adListData = new BannerListData();
//            banner_adListData.setImage_url("http://img0.imgtn.bdimg.com/it/u=3215222857,1774393785&fm=26&gp=0.jpg");
            banner_adListData.setImage_url(R.drawable.base_img_default_square);
            mBannerList.getList().add(banner_adListData);
        }
        setBannerView();
    }

    void setBannerView() {

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) banner_ad.getLayoutParams();
        params.width = FrameLayout.LayoutParams.MATCH_PARENT;
        params.height = SystemParamsUtils.getScreenWidth() * 30 / 75;
        banner_ad.setLayoutParams(params);
        ArrayList<Object> listImgs = new ArrayList<>();
        ArrayList<String> listTitles = new ArrayList<>();

        for (int i = 0; i < mBannerList.getList().size(); i++) {
//            listImgs.add("http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png");
//            listImgs.add(mBannerList.getList().get(i).getImage_url75x30());
            listImgs.add(mBannerList.getList().get(i).getImage_url());
            listTitles.add(mBannerList.getList().get(i).getTitle());
        }
//        if (listBanner == null) {
//            listImgs = new ArrayList<>();
//            listTitles = new ArrayList<>();
//        } else {
//            listImgs = listBanner.getListImage();
//            listTitles = listBanner.getListTitle();
//        }
        //设置banner_ad样式
        banner_ad.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置指示器位置（当banner_ad模式中有指示器时）
        banner_ad.setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载器
        banner_ad.setImageLoader(new GlideImageLoader(R.drawable.base_img_default_square));
        //设置图片集合
        banner_ad.setImages(listImgs);
        //设置banner_ad动画效果
//        banner_ad.setBannerAnimation(getRandomTransfer());
//        banner_ad.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner_ad样式有显示title时）
        banner_ad.setBannerTitles(listTitles);
        //设置自动轮播，默认为true
        banner_ad.isAutoPlay(true);
        //设置轮播时间
        banner_ad.setDelayTime(3000);
        //banner_ad设置方法全部调用完毕时最后调用
        banner_ad.start();

        banner_ad.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                BannerListData data = mBannerList.getList().get(position);
//                data.open(mContext);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            refreshData();
        }
    }


    public class AdapterEnter extends RecyclerView.Adapter<AdapterEnter.ViewHolder> {

//        BasisActivity mContext;

//        BaseListDataListBean mListBean;
        boolean isCompany = false;
        public AdapterEnter() {

            isCompany = LoginBean.getInstance().getUserInfo().isUserCompany();
        }


        //创建新View，被LayoutManager所调用
        @Override
        public AdapterEnter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.home_enter_grid_item, viewGroup, false);
            return new AdapterEnter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(AdapterEnter.ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            if(isCompany){
                return mListBeanEnter == null ? 0 : mListBeanEnter.getList().size();
            }
//            return mListBeanEnter == null ? 0 : (mListBeanEnter.isMore() ? HomeGrideListBean.MAX_SHOW : mListBeanEnter.getList().size());
            return mListBeanEnter == null ? 1 : (mListBeanEnter.isMore() ? HomeGrideListBean.MAX_SHOW : (mListBeanEnter.getList().size() + 1));

        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_count)
            public TextView text_count;
            @BindView(R.id.img_icon)
            public ImageView img_icon;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
//                if (mListBeanEnter.isMore() && position == (HomeGrideListBean.MAX_SHOW - 1)) {
                text_count.setVisibility(View.GONE);

                if (position == getItemCount() - 1 && !isCompany) {
                    text_name.setText("更多");
                    img_icon.setImageResource(R.drawable.home_icon_more);
                } else {
                    HomeGrideListData data = mListBeanEnter.getList().get(position);
                    text_name.setText(data.getName());
                    BasisApp.loadImg(mContext, data.getIconUrl(), img_icon, R.drawable.base_img_default_square);
                    if (!TextUtils.isEmpty(data.getUnReadCountMsg())) {
                        text_count.setVisibility(View.VISIBLE);
//                        text_count.setText(data.getUnReadCountMsg()+"");
                    }
                }

                list_item.setTag(position);
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                int position = (int) v.getTag();
//                if (mListBeanEnter.isMore() && position == (HomeGrideListBean.MAX_SHOW - 1)) {
                if (position == getItemCount() - 1 && !isCompany) {

                    ActivityTool.skipActivityForResult(mContext, HomeAppActivity.class, 1);
                    return;
                }
                HomeGrideListData data = mListBeanEnter.getList().get(position);
                data.onItemClick(mContext);
            }
        }
    }

    void checkCacheAndDownload() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        if (msp.isFirst(mContext)) {
            LogUtil.i("第一次打开  或者 通讯录缓存不存在--直接更新->");
            msp.setFirstDone(mContext);
            getContactList();
        } else {
            msp.setFirstDone(mContext);
        }
    }

    UserBaseInfoUpdateCache cacheOld;

    void getMapCenter() {
        MyParams params = new MyParams();
        showProgress();
        params.put("code", "DEFAULT_MAP_CENTER");
        MyHttpUtils.post(Constants.URL_USER_GET_DICTIONARY_BYCODE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        UserDictBean dictBean = (UserDictBean) result;
                        if (!TextUtils.isEmpty(dictBean.getDictValue())) {
                            String[] locationstr = dictBean.getDictValue().split(",");
                            double latitude = Double.valueOf(locationstr[1]);
                            double longtitude = Double.valueOf(locationstr[0]);
                            double[] locations = GPSUtil.gps84_To_Gcj02(latitude, longtitude);
                            AMapLocUtil.mMapCenterLatLng = new LatLng(locations[0], locations[1]);
                        }

                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, UserDictBean.class);
    }

    private void getContactList() {
        MyParams params = new MyParams();
//        showProgress();
        params.put("showAll", "false");
        MyHttpUtils.post(Constants.URL_USER_CONTACT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        ContactListBean mListBean = (ContactListBean) result;
                        mListBean.save();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                    }
                },
                0, ContactListBean.class);

    }

    private void getListEnterAll() {

        MyParams params = new MyParams();
        params.put("projectNo", Constants.PROJECT_NO);
        MyHttpUtils.post(Constants.URL_USER_AUTHORITY_APP, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mListBeanEnterAll = (HomeGrideListBean) result;
                        mListBeanEnterAll.saveObj();
                        setNewsView();
                        if (mListBeanEnterAll.searchDataByName("警情管理") == null) {
                            view_today_num_zone.setVisibility(View.GONE);
                        } else {
                            view_today_num_zone.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
//            mListBean = new ServiceNewListBean();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, HomeGrideListBean.class);

    }


    public class TodayOndutyPersonAdapter extends RecyclerView.Adapter<TodayOndutyPersonAdapter.ViewHolder> {
        HomeOndutyPersonListBean mListBean;
        public TodayOndutyPersonAdapter(HomeOndutyPersonListBean listBean) {
            mListBean = listBean;
        }

        //创建新View，被LayoutManager所调用
        @Override
        public TodayOndutyPersonAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.home_onduty_person_grid_item, viewGroup, false);
            return new TodayOndutyPersonAdapter.ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(TodayOndutyPersonAdapter.ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_xiegang)
            public TextView text_xiegang;
            @BindView(R.id.text_name)
            public TextView text_name;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                HomeOndutyPersonListData data = mListBean.getList().get(position);
                text_name.setText(data.getDutyPostShort() + ": " + data.getDutyUserName());
                if (position == 0) {
                    text_xiegang.setVisibility(View.INVISIBLE);
                } else if (position > 2 && ((position - 3) % 4 == 0)) {
                    text_xiegang.setVisibility(View.INVISIBLE);
                } else {
                    text_xiegang.setVisibility(View.VISIBLE);
                }
                list_item.setTag(position);
            }
        }
    }

    @Subscribe
    public void onHomeIndexEvent(EventHomeIndex event) {
        if (isFinishing()) return;
        LogUtil.i("onHomeIndexEvent---->");

        if (EventHomeIndex.TYPE_WARN_UNREAD_COUNT_REFRESH == event.type) {
            getWarnUnReadCount();
        } else if (EventHomeIndex.TYPE_NEWS_REFRESH == event.type) {
            mHandler.sendEmptyMessage(MESSAGE_NEWS_REFRESH);
        } else {
            mHandler.sendEmptyMessage(MESSAGE_NEWS_REFRESH);
        }
//                getNews();
    }

    public static class EventHomeIndex {

        public static final int TYPE_WARN_UNREAD_COUNT_REFRESH = 2;
        public static final int TYPE_NEWS_REFRESH = 1;
        int type;

        public EventHomeIndex(int type) {
            this.type = type;
        }
    }

    BasisBean mWarnUnReadCount;

    private void getWarnUnReadCount() {
        MyParams params = new MyParams();
        MyHttpUtils.post(Constants.URL_WARN_GET_UNREAD_COUNT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mWarnUnReadCount = (BasisBean) result;
                        setWarnUnRead();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                        mWarnUnReadCount = new BasisBean();
                        mWarnUnReadCount.setResultData("0");
                        setWarnUnRead();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, BasisBean.class);

    }

    void setWarnUnRead() {
        if (mWarnUnReadCount == null) return;
        if (mListBeanEnter == null) return;
        mListBeanEnter.setWarnUnReadCount(Integer.valueOf(mWarnUnReadCount.getResultData()));
        recyclerView_grid.setAdapter(new AdapterEnter());
    }

    private void checkSmsObserver() {
        if(LoginBean.getInstance().getUserInfo().isUserCompany() ||LoginBean.getInstance().getUserInfo().isRedUser() ){
            if(smsObserver != null){
                smsObserver.unregisterSMSObserver();
                smsObserver = null;
            }
        }else {
            if (smsObserver == null) {
                smsObserver = new SmsObserver(mContext, HomeIndexActivity.this);
                smsObserver.setSmsFilter(new MySmsFilter());
                smsObserver.registerSMSObserver();
            }
        }
    }

    @Override
    public void onCallbackSmsContent(SmsInfoBean smsInfoBean) {
        if (smsInfoBean == null) return;
        if (TextUtils.isEmpty(smsInfoBean.getBody())) return;
        UserSensitiveWordsBean sensitiveWordsBean = UserSensitiveWordsBean.getFromCache();
        if (sensitiveWordsBean == null) return;

        if(TextUtils.isEmpty(smsInfoBean.getAddress()))return;

        if(LoginBean.getInstance().getUserInfo().isUserCompany())return;
        if(LoginBean.getInstance().getUserInfo().isRedUser())return;



        LogUtil.i("onCallbackSmsContent--->" + JSONObject.toJSONString(smsInfoBean));

        MySharedPreferences msp =new MySharedPreferences(mContext);
        String lastId = msp.getString("sms_last_upload_id");
        if(!TextUtils.isEmpty(lastId) && smsInfoBean.getId().equals(lastId)){
            LogUtil.i("onCallbackSmsContent--->" + "重复短信？？");
            return;
        }
//        MySharedPreferences msp =new MySharedPreferences(mContext);
        msp.putString("sms_last_upload_id",smsInfoBean.getId());

        MyParams params = new MyParams();
        params.put("imei",MyUtils.getIMEI());
        params.put("sensitiveWord",sensitiveWordsBean.getSenstivieWords(smsInfoBean.getBody()));
        params.put("sensitiveContent",smsInfoBean.getBody());
        params.put("sensitiveApp","短信");
        params.put("sendObject",getSmsSendOrReceiveContent(smsInfoBean,true));
        params.put("receiveObject",getSmsSendOrReceiveContent(smsInfoBean,false));
        if(AMapLocUtil.mLocation != null){
            double[] location = GPSUtil.gcj02_To_Gps84(AMapLocUtil.mLocation.getLatitude(), AMapLocUtil.mLocation.getLongitude());
            params.put("longitude", location[1]);
            params.put("latitude", location[0]);
            params.put("address", AMapLocUtil.mLocation.getAddress());
        }

        MyHttpUtils.post(Constants.URL_USER_SENSITIVEWORDS_UPLOAD, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {


            }

            @Override
            public void onFailure(int httpWhat, Object result) {
//                super.onFailure(httpWhat, result);
            }

            @Override
            public void onFinish(int httpWhat) {

            }
        }, 0, BasisBean.class);
    }
    private String getSmsSendOrReceiveContent(SmsInfoBean smsInfoBean,boolean isSend){
        boolean isInSendBox = smsInfoBean.getStatus().equals(SmsInfoBean.STATUS_SEND_COMPLETED);
        StringBuilder builder = new StringBuilder();
        boolean isMyInfo  = true;
        if(isInSendBox){
            isMyInfo = isSend;
        }else {
            isMyInfo = !isSend;
        }
        if(isMyInfo){
//            UserInfoBean userInfoBean = LoginBean.getInstance().getUserInfo();
//            MySharedPreferences mySharedPreferences = new MySharedPreferences(mContext);
//            builder.append("名称："+userInfoBean.getName()).append("手机："+mySharedPreferences.getUser());
            builder.append("--");
        }else {
            builder.append(smsInfoBean.getSendObjectSTR());
        }
        return builder.toString();
    }

    private void getSensitiveWords() {
        MyParams params = new MyParams();
        MyHttpUtils.post(Constants.URL_USER_SENSITIVEWORDS_GET_WORDS, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        BasisBean basisBean = (BasisBean) result;
                        UserSensitiveWordsBean sensitiveWordsBean = new UserSensitiveWordsBean();
                        if (!TextUtils.isEmpty(basisBean.getResultData())) {
                            sensitiveWordsBean.setList((ArrayList<String>) JSONObject.parseArray(basisBean.getResultData(), String.class));
                        }
                        sensitiveWordsBean.save();
//                        LogUtil.i("sensitiveWordsBean---->" + sensitiveWordsBean.getList().size());
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, BasicBeanStr.class);

    }

    private void uploadPhoneInfo() {
        if(!LoginBean.isLogin())return;
        if(LoginBean.getInstance().getUserInfo().isUserCompany())return;
        if(LoginBean.getInstance().getUserInfo().isRedUser())return;
        MySharedPreferences msp = new MySharedPreferences(mContext);
        String appsNow = StringUtil.StringGroupToStr(MyUtils.getAppList(mContext));
        String sp_key = "ff_apps_"+LoginBean.getUserId();
        String appsOld = msp.getString(sp_key);
        if(!TextUtils.isEmpty(appsNow) && !TextUtils.isEmpty(appsOld) && appsNow.equals(appsOld)){
            return;
        }

        MyParams params = new MyParams();
        params.put("imei",MyUtils.getIMEI());
        params.put("brand",android.os.Build.BRAND);
//        params.put("deviceName", android.os.Build.DEVICE);
        params.put("deviceName", SystemParamsUtils.getDeviceName(mContext));
        params.put("model", android.os.Build.MODEL);
        params.putObj("apps",MyUtils.getAppList(mContext));
        MyHttpUtils.post(Constants.URL_USER_PHONEINFO_UPLOAD, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing())return;
                        new MySharedPreferences(mContext).putString("ff_apps_"+LoginBean.getUserId(),StringUtil.StringGroupToStr(MyUtils.getAppList(mContext)));
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, BasisBean.class);

    }


    private void refreshLoginInfo() {
        MyParams params = new MyParams();
        params.put("projectNo",Constants.PROJECT_NO);
        params.put("appType","APP");
        MyHttpUtils.post(Constants.URL_USER_REFRESH_LOGININFO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        UserInfoBean bean = (UserInfoBean) result;
                        LoginBean loginBean = LoginBean.getInstance();
                        loginBean.setUserInfo(bean);
                        loginBean.save();
                        checkSmsObserver();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
//                        dismissProgress();
                    }
                },
                0, UserInfoBean.class);

    }

}
